<template>
	<view class="collapse">
		<block v-for="(item, index) in items" :key="index">
			<view class="collapse-item" @click="toggle(index)">
				<view class="collapse-header">
					<text class="collapse-title">{{ item.head }}</text>
					<text class="collapse-arrow" :class="{ 'rotate': activeIndex === index }">▼</text>
				</view>
				<view class="collapse-content" v-if="activeIndex === index">

					<!-- 使用 v-slot 解构插槽 scope -->
					<slot name="content" :item="item">
						{{ item.body }}
					</slot>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	export default {
		name: "collapse",
		props: {
			items: {
				type: Array,
				required: true,
				default: () => []
			},
			accordion: {
				type: Boolean,
				default: false // 是否开启手风琴模式
			}
		},
		data() {
			return {
				activeIndex: this.accordion ? null : [] // 手风琴模式下只记录一个索引，否则记录多个
			};
		},
		methods: {
			toggle(index) {
				if (this.accordion) {
					// 手风琴模式：只有一个展开项
					this.activeIndex = this.activeIndex === index ? null : index;
				} else {
					// 多个可展开模式
					const isActive = this.activeIndex.includes(index);
					if (isActive) {
						this.activeIndex = this.activeIndex.filter(i => i !== index); // 移除当前索引
					} else {
						this.activeIndex.push(index); // 添加当前索引
					}
				}
			}
		}
	};
</script>

<style scoped>
	.collapse {
		width: 100%;
	}

	.collapse-item {
		border-bottom: 1px solid #ebebeb;
	}

	.collapse-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #f9f9f9;
		font-size: 16px;
		cursor: pointer;
	}

	.collapse-title {
		font-weight: bold;
	}

	.collapse-arrow {
		transition: transform 0.3s ease;
	}

	.collapse-arrow.rotate {
		transform: rotate(180deg);
	}

	.collapse-content {
		padding: 10px;
		font-size: 14px;
		line-height: 1.5;
	}
</style>